import { ABP, ListService, PagedAndSortedResultRequestDto } from '@abp/ng.core';
import { Component, Input, OnInit, TrackByFunction } from '@angular/core';
import { IdentityRoleService } from '../proxy/identity';
import { IdentityRoleDto } from '../proxy/identity/models';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { AbstractControl } from '@angular/forms';
import snq from 'snq';

@Component({
  selector: 'lib-ref-select-role',
  templateUrl: './ref-select-role.component.html',
  providers: [ListService],
})
export class RefSelectRoleComponent implements OnInit {
  models: IdentityRoleDto[] = [];
  totalCount: number = 0;

  public trackByFn: TrackByFunction<AbstractControl> = (index, item) =>
    Object.keys(item)[0] || index;

  public get currentPage() {
    return this.listService.page + 1;
  }

  public set currentPage(page: number) {
    this.listService.page = Math.max(page - 1, 0);
  }

  public get maxResultCount() {
    return this.listService.maxResultCount;
  }

  public set maxResultCount(value: number) {
    this.listService.maxResultCount = value;
  }

  @Input() selectedModels: IdentityRoleDto[] = [];
  @Input() selectMode: 'single' | 'multiple' = 'single';

  constructor(
    public readonly listService: ListService<PagedAndSortedResultRequestDto>,
    public modalRef: NzModalRef,
    public entityService: IdentityRoleService
  ) {}

  ngOnInit(): void {
    this.listService.maxResultCount = 10;
    this.listService
      .hookToQuery(query => this.entityService.getList(query))
      .subscribe(listResult => this.renderModels(listResult));
  }

  renderModels(listResult) {
    this.models = listResult.items;
    this.totalCount = listResult.totalCount;
  }

  isModelSelected(item: IdentityRoleDto) {
    return !!snq(() => this.selectedModels.find(x => x.id == item.id));
  }

  setCurrentModel(item: IdentityRoleDto) {
    if (this.selectMode == 'single') {
      if (!this.selectedModels?.length) {
        this.selectedModels = [item];
      } else {
        if (this.selectedModels[0] == item) this.selectedModels = [];
        else this.selectedModels = [item];
      }
    } else {
      if (this.isModelSelected(item)) {
        this.selectedModels = snq(() => this.selectedModels.filter(x => x.id != item.id));
      } else {
        this.selectedModels = [...snq(() => this.selectedModels), item];
      }
    }
  }

  setCurrentModelAndSubmit(item: IdentityRoleDto) {
    if (this.selectMode == 'single') {
      this.selectedModels = [item];
      this.submitForm();
    } else {
      if (this.isModelSelected(item)) {
        this.selectedModels = snq(() => this.selectedModels.filter(x => x.id != item.id));
      } else {
        this.selectedModels = [...snq(() => this.selectedModels), item];
      }
    }
  }

  cancelForm() {
    this.modalRef.close(null);
  }

  submitForm() {
    var selectedModels = !this.selectedModels?.length ? null : this.selectedModels;
    this.modalRef.close(selectedModels);
  }
}
